import { getuuid } from ".";
var chars = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
];
var prefix = "SH";
let linesOptions = {

}
let source = null,
  target = null;

let stationsObj = {};

let pen = [];

let lineNetObj = {}
export const handleLineNet = function handleLineNet(lineNet) {
  lineNetObj = initLine(lineNet);
  Object.values(lineNetObj).forEach((lineroad) => {
    handleLineRoad(lineroad);
  });

  window.$graph.fromJSON(pen);
  return linesOptions;
}

function createLink(source, target, info) {
  // 处理 1004 需求
  let realSource = pen.filter(p => p.id === source.id)[0];
  let realTarget = pen.filter(p => p.id === target.id)[0];
  // links
  let realSourceLinks = realSource.data.links;
  let realTargetLinks = realTarget.data.links;
  let flag = "";
  let realTargetLinksObj = {};
  realTargetLinks.forEach(link => {
    realTargetLinksObj[link] = true;
  })
  for (let i = 0; i < realSourceLinks.length; i++) {
    const rlink = realSourceLinks[i];

    if (realTargetLinksObj[rlink]) {
      flag = rlink;
      break;
    }
  }

  if (flag) {
    let edge = pen.filter(p => p.id === flag)[0];
    // edge
    let { tags, ln, ldbm } = edge.data;
    if (!tags.includes(info.dbm)) {
      edge.data.tags.push(info.dbm);
    }
    if (!ln.includes(info.realName)) {
      edge.data.ln.push(info.realName);
    }
    if (!ldbm.includes(info.dbm)) {
      edge.data.ldbm.push(info.dbm);
    }
    return null;
  } else {
    let edgeid = getuuid(4);
    let edge = {
      id: edgeid,
      shape: "edge",
      attrs: {
        line: {
          targetMarker: null,
          sourceMarker: null,
          stroke: info.color,
        },
      },
      source: { cell: source.id },
      target: { cell: target.id },
      zIndex: 12,
      data: {
        tags: ["line", info.dbm],
        ln: [info.realName],
        ldbm: [info.dbm],
        from: source.id,
        to: target.id
      },
    };
    pen.push(edge);
    return edgeid;
  }


}

function handlelineName(linename) {
  let linenames = [];
  // 根据 逗号  分隔
  let linesBlock = linename.split(",");
  linesBlock = linesBlock.filter(item => item)
  // 根据 | 分隔
  linesBlock.forEach(lineblock => {
    let lineNameBlocks = lineblock.split("|")[1];
    let splitIndex = lineNameBlocks.indexOf("线");
    let name = lineNameBlocks.substring(0, splitIndex + 1);
    linenames.push(name)
  })
  // 根据 线 分隔
  return linenames
}


function handleStation(station, index, info) {
  let circle = {
    // position
    size: {
      width: 8,
      height: 8,
    },
    shape: "circle",
    zIndex: 5,
    attrs: {
      body: {
        fill: "#fff",
        stroke: "#ccc",
        strokeWidth: 2,
      },
    },
    data: {}
  }
  let textNode = {
    // position
    size: { width: 1, height: 1 },
    shape: "rect",
    zIndex: 10,
    attrs: {
      body: {
        fill: "transparent",
        stroke: "transparent",
        width: 0,
      },
      label: {
        text: "",
        fill: "#fff",
        fontSize: 12,
      },
    },
    data: {
      type: "text",
      tags: ["text"],
    }
  };
  if (!stationsObj[station.name]) {
    stationsObj[station.name] = true;
    // 将station转为x6的node
    let stationId = getuuid(6);

    circle.id = stationId;
    circle.position = {
      x: parseInt(station.x),
      y: parseInt(station.y)
    }
    let lns = handlelineName(station.line);
    circle.data = {
      tags: ["station"],
      sn: station.name,
      sdbm: "ABC",
      ln: lns,
      ldbm: lns.map(item => lineNetObj[item] && lineNetObj[item].dbm),
      links: []
    }

    // 处理文本节点
    let textId = stationId + "-text";
    textNode.id = textId;
    textNode.position = {
      x: parseInt(station.x) + 4,
      y: parseInt(station.y) - 12
    }
    textNode.attrs.label.text = station.name;
    pen.push(circle)
    pen.push(textNode);
  } else {
    // 处理已经存在的
    circle = pen.filter(p => p.data.sn === station.name)[0];
  }
  // 处理连线

  if (index == 0) {
    target = circle
  } else {
    source = target;
    target = circle
    let edgeId = createLink(source, target, info);
    if (edgeId) {
      let sourceLinks = pen.filter(p => p.id === source.id)[0].data.links;
      if (!sourceLinks.includes(edgeId)) {
        pen.filter(p => p.id === source.id)[0].data.links = [...sourceLinks, edgeId];
      }

      let targetLinks = pen.filter(p => p.id === target.id)[0].data.links;
      if (!targetLinks.includes(edgeId)) {
        pen.filter(p => p.id === target.id)[0].data.links = [...targetLinks, edgeId];
      }
    }



  }

}

function handleLine(line, info) {
  source = null; target = null;
  line.forEach((station, index) => {
    handleStation(station, index, info)
  })
}

function handleLineRoad(lineroad) {
  let { lines, color, dbm, realName } = lineroad;
  let info = {
    color,
    dbm,
    realName
  }
  lines.forEach(line => {
    handleLine(line, info);
  })
}

function initLine(lineNetData) {
  let lineNetObj = {};
  let i = 0;
  lineNetData &&
    Array.isArray(lineNetData) &&
    lineNetData.forEach((lineroad) => {
      if (lineroad.name.includes("线")) {
        let splitIndex = lineroad.name.indexOf("线");
        let name = lineroad.name.substring(0, splitIndex + 1);
        lineroad.dbm = prefix + chars[i];
        lineroad.color = "";
        lineroad.realName = name;
        if (!lineNetObj[name]) {
          // 如果不存在，就添加进去
          linesOptions[name] = {
            name: name,
            dbm: prefix + chars[i],
            color: lineroad.stations[0].col, // 线路的颜色
            status: 1
          }
          lineNetObj[name] = {
            name: lineroad.name,
            realName: name,
            dbm: prefix + chars[i],
            color: lineroad.stations[0].col, // 线路的颜色
            lines: [lineroad.stations],
          };
          i++;
        } else {
          lineNetObj[name].lines.push(lineroad.stations);
        }
      }
    });
  return lineNetObj;
};


